package edu.purdue.cs.aggr.messageprocessor;

import edu.purdue.cs.aggr.AggrException;
import edu.purdue.cs.aggr.Vertex;
import edu.purdue.cs.aggr.VertexManager;
import edu.purdue.cs.aggr.message.EventMessageBuilder;
import edu.purdue.cs.aggr.message.Message;
import edu.purdue.cs.aggr.message.VertexTransferMessage;
import edu.purdue.cs.aggr.message.EventNotificationMessage.Event;

public class VertexTransferMessageProcessor extends MessageProcessor 
{
  private VertexManager manager;

  public VertexTransferMessageProcessor(VertexManager manager)
  {
    this.manager = manager;
  }

  @Override
  public synchronized void processMessage(Message message) throws AggrException
  {
    VertexTransferMessage transferMessage = (VertexTransferMessage) message;
    
    Vertex v = transferMessage.getVertex();
    // copy Vertex received into our Vertex list
    manager.addNode(v);
    
    // tell controller we received a vertex
    manager.sendMessage(EventMessageBuilder.createEventMessage(manager, Event.VERTEX_RECEIVED, null));
    
    // start the Vertex
    System.out.println("Preparing to start vertex: " + v.toString());
    
    new Thread(v).start();
    System.out.println("Started " + v.getId() + " on manager " + manager.getId());
  }
}
